#Author: Salvatore Gionfriddo
from Environment import Environment
class TicTacToeEnvironment(Environment):
    def __init__(self):
        self.empty = 0
        self.x = 1
        self.o = -1
        self.turn = self.x
        e = self.empty
        self.board = [e,e,e,e,e,e,e,e,e]
    def resetBoard(self):
        self.turn = self.x
        e = self.empty
        self.board = [e,e,e,e,e,e,e,e,e]
    def performAction(self, action):
        action = int(action)
        reward = 0
        end = 'Game On'
        #place piece
        if self.board[action] == self.empty:
            self.board[action] = self.turn
        #check for win
        end_games = {0:[(1,2),(3,6),(4,8)], 1:[(4,7)], 2:[(4,6),(5,8)], 3:[(4,5)], 6:[(7,8)]}
        for tic in end_games:
            if self.board[tic] == self.turn:
                for tac,toe in end_games[tic]:
                    if self.board[tac] == self.turn and self.board[toe] == self.turn:
                        #you win
                        reward = 1
                        end = 'Win'
        #if no win check for tie
        if reward == 0:
            tie = True
            for spot in self.board:
                if spot == self.empty:
                    tie = False
                    break
            if tie:
                end = 'Tie'
        #change turns
        if self.turn == self.x:
            self.turn = self.o
        else:
            self.turn = self.x
        state = self.getState()
        return (state, reward, end)
    def getAvailableActions(self):
        actions = []
        i = 0
        for space in self.board:
            if space == self.empty:
                actions.append(1)
            else:
                actions.append(0)
        return actions
    def getState(self):
        return self.board
